package org.rabbitmq.mq02.common;

import java.io.*;

/**
 * 消息序列化和反序列化工具,将所有方法都用static修饰,直接通过类名调用方法
 * 序列化:将对象转化为字节数组
 * 反序列化:将字节数组转化为对象
 */
public class BinaryTool {
    //序列化: 将对象转为字节数组
    //将Object序列化的数据逐渐写到ByteArrayOutputStream中,再转换为byte[]
    public static byte[] toByte(Object object) throws IOException {
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)){
                //writeObject方法就会将对象进行序列换,转换为二进制数据写入到ObjectOutputStream中,
                //由于ObjectOutputStream又关联了ByteArrayOutputStream,
                //于是最终就写入到了ByteArrayOutputStream中
                objectOutputStream.writeObject(object);
            }
            return byteArrayOutputStream.toByteArray();
        }
    }
    //反序列化: 将字节数组转化为对象
    public static Object fromBytes(byte[] bytes) throws IOException, ClassNotFoundException {
        Object object = null;
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)) {
            try(ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)){
                object = objectInputStream.readObject();
            }
        }
        return object;
    }
}
